﻿using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.WebAPI.Filter;
using Dm.Config;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.FileSystemGlobbing.Internal;
using NetTaste;
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Security.Claims;
using System.Text.RegularExpressions;

namespace DFGK_WMS.WebAPI.Controllers
{
    // [Route("api/[controller]")]
    // [ApiController]
    //[NonController()]
    public class BaseController : ControllerBase
    {
        private readonly DFGK_DB _DBContext;

        public BaseController(DFGK_DB dBContext)
        {
            _DBContext = dBContext;
        }


        /// <summary>
        /// 生成单号
        /// </summary>
        /// <param name="operationEnum"></param>
        /// <returns></returns>
        protected string CreateOrderID(OperationEnum operationEnum)
        {
            //去并发
            Random rnd = new Random(Guid.NewGuid().GetHashCode());
            int randNum = rnd.Next(1, 10000);
            //去重 
            string str = DateTime.Now.ToString("yyyyMMddHHmmssfff") + randNum.ToString("0000");
            switch (operationEnum)
            {
                case OperationEnum.Out:
                    return "O" + str;

                case OperationEnum.In:
                    return "I" + str;
                case OperationEnum.Remove:
                    return "M" + str;
                default:
                    return str;
            }

        }


        /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        protected bool Log(string msg)
        {
            return Log(msg, null);
        }

        /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected bool Log(string msg, string data)
        {
            //控制器模块描述
            string apiModule = string.Empty;
            var controllerAttribute = GetType().GetCustomAttribute<HeadAttribute>(false);
            if (controllerAttribute != null)
            {
                apiModule = controllerAttribute._Description;
            }

            //当前登录人
            string currentUserName = HttpContext?.User?.Claims?.FirstOrDefault(t => t.Type == "UserName")?.Value;
            string currentRealName = HttpContext?.User?.Claims?.FirstOrDefault(t => t.Type == "RealName")?.Value;
            string currentJobNo = HttpContext?.User?.Claims?.FirstOrDefault(t => t.Type == "JobNo")?.Value;

            //操作目标
            object? attrbiute = HttpContext.GetEndpoint().Metadata.Where(t => t.GetType().Equals(typeof(FunctionAttribute)))?.FirstOrDefault();
            string actionModule = string.Empty;
            if (attrbiute != null)
            {
                FunctionAttribute? attributeObject = attrbiute as FunctionAttribute;
                actionModule = attributeObject._Description;
            }

            //object? controllerName = HttpContext.GetRouteValue("controller");
            //object? actionName = HttpContext.GetRouteValue("action");
            string apiDescription = $"[[{msg}]-[{data}]]";
            string module = $"[{apiModule}-{actionModule}]";

            TLog log = new TLog()
            {
                CreateDate = DateTime.Now,
                Description = apiDescription,
                UserName = currentUserName,
                RealName = currentRealName,
                ModuleName = module,
                LogType = 1,
                UserRemark = currentJobNo,
                ActionType = 0

            };
            _DBContext.Set<TLog>().Add(log);
            return _DBContext.SaveChanges() > 0;


        }

        /// <summary>
        /// 获取当前人
        /// </summary>
        /// <returns>(登录人id，登录人姓名，登录人工号)</returns>
        protected (int, string, string) GetUserInfo()
        {

            int userId = string.IsNullOrEmpty(HttpContext?.User.FindFirst("Id")?.Value) ? 0 : Convert.ToInt32(HttpContext?.User.FindFirst("Id")?.Value);
            string userName = HttpContext?.User.FindFirst("UserName")?.Value;
            string userJobId = HttpContext?.User.FindFirst("JobNo")?.Value;

            return (userId, userName, userJobId);

        }


        protected string CreateCode(string code, int type)
        {
            if (string.IsNullOrEmpty(code))
            {
                return null;
            }


            MatchCollection matches = Regex.Matches(code, @"\d+");
            if (matches.Count <= 0)
            {
                return null;
            }

            //int padNumber = 4;
            string value = matches[i: matches.Count - 1].Value;

            int id = Convert.ToInt32(value);
            ++id;

            string newCode = id.ToString("0000");

            switch (type)
            {
                case 1:

                    newCode = "Customer" + newCode;
                    break;


                default:

                    break;
            }

            return newCode;



        }
    }
}
